package com.br.semperparata.components.gui;

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class CheckBoxList<E> extends JPanel {
	private static final long serialVersionUID = 1L;
	
	private GridLayout grid = null;
	private JPanel checkPanel = null;
	private List<JCheckBox> checks = null;
	private JLabel label = null;
	
	public CheckBoxList() {
		this(null, null, 0, 1);
	}
	
	public CheckBoxList(String label) {
		this(label, null, 0, 1);
	}
	
	public CheckBoxList(List<E> items) {
		this(null, items, 0, 1);
	}
	
	public CheckBoxList(List<E> items, int rows, int cols) {
		this(null, items, rows, cols);
	}
	
	public CheckBoxList(String label, List<E> items, int rows, int cols) {
		super(new FlowLayout(FlowLayout.LEADING, 5, 5));
		
		if (label != null) {
			this.label = new JLabel(label);
			this.add(this.label);
		}
		
		this.grid = new GridLayout(rows, cols);
		this.checkPanel = new JPanel(this.grid);
		
		this.checks = new ArrayList<JCheckBox>();
		for (E item : items) {
			JCheckBox cb = new JCheckBox(item.toString());
			checks.add(cb);
		}
		
		if (checks != null) {
			for (JCheckBox cb : checks)
				this.checkPanel.add(cb);
		}
		this.add(this.checkPanel);
	}
	
	public CheckBoxList<E> addListener(EventListener listener) {
		if (listener instanceof ItemListener)
			for (JCheckBox cb : checks)
				cb.addItemListener((ItemListener)listener);
		else if (listener instanceof ActionListener)
			for (JCheckBox cb : checks)
				cb.addActionListener((ActionListener)listener);
		return this;
	}
	
	public void setLabelFont(Font font) {
		if (this.label != null)
			this.label.setFont(font);
	}
	
	public void setCheckBoxesFont(Font font) {
		for (JCheckBox cb : checks)
			cb.setFont(font);
	}
	
	public void setFonts(Font font) {
		setLabelFont(font);
		setCheckBoxesFont(font);
	}

}
